//
//  AppDelegate.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/20.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "AppDelegate.h"
#import "SDWebImageManager.h"
#import "iVersion.h"
#import "MobClick.h"
#import "UMFeedback.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "CYABTool.h"
#import "CYDatabase.h"
#import "CYMeTool.h"
#import "CYHttpTool.h"
#import "CYTool.h"
#import "CYCallCenter.h"
#import "JPUSHService.h"
#import "CYLoginHttpTool.h"
#import "CYMessageViewController.h"
#import "UMCheckUpdate.h"
#import <JSPatch/JSPatch.h>
#import <ZMCreditSDK/ALCreditService.h>
#import "TAdLaunchImageView.h"
#import "UIImage+TYLaunchImage.h"
#import "TYLaunchFadeScaleAnimation.h"
#import "TYLaunchBaseAnimation.h"
#import "UIView+TYLaunchAnimation.h"
#import "hDisplayView.h"
#import <AVFoundation/AVFoundation.h>
#import "UMessage.h"
#import <AdSupport/AdSupport.h>

#define kStoreAppId @"1052661395"  // （appid数字串
#define MainScreen_width  [UIScreen mainScreen].bounds.size.width//宽
#define MainScreen_height [UIScreen mainScreen].bounds.size.height//高
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     
     //注册芝麻分
     [[ALCreditService  sharedService] resgisterApp];
     //启动图2
     hDisplayView *hvc = [[hDisplayView alloc]initWithFrame:CGRectMake(0, 0, MainScreen_width, MainScreen_height)];
     [self.window.rootViewController.view addSubview:hvc];
     [UIView animateWithDuration:0.01 animations:^{
          hvc.frame = CGRectMake(0, 0, MainScreen_width, MainScreen_height);
          
     }];
     
     //Jpush  apsForProduction:NO为开发环境，YES为生产环境
     [JPUSHService setupWithOption:launchOptions appKey:@"3656a84c5156131ca16b6d88"
                           channel:nil
                  apsForProduction:YES
             advertisingIdentifier:nil];
     
     [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
     
//     CYUser *user = [CYLoginHttpTool userData].user;
//     //别名
//     [JPUSHService setAlias:user.userId callbackSelector:@selector(tagsAliasCallback:) object:nil];
     
     @try {
          //同步推渠道包
//                  [MobClick startWithAppkey:UMAppkey reportPolicy:BATCH channelId:@"PushSynchronization"];
          //91助手渠道包
//                  [MobClick startWithAppkey:UMAppkey reportPolicy:BATCH channelId:@"91助手"];
          //服务器渠道包
          [MobClick startWithAppkey:UMAppkey reportPolicy:BATCH channelId:@""];
          
          [UMFeedback setAppkey:UMAppkey];
          [UMSocialData setAppKey:UMAppkey];
          //设置微信AppId，设置分享url，默认使用友盟的网址
          [UMSocialWechatHandler setWXAppId:@"wx4aac420af2e95596" appSecret:@"3e4a54697703f24179b8ce2d1b3f088a" url:@"www.credit-manage.com"];
          //设置分享到QQ空间的应用Id，和分享url 链接
          [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"www.credit-manage.com"];
          
          //检查version更新 appstore备用
          [CYHttpTool getSerializerWithURL:@"https://dn-ipaplist.qbox.me/CreditAddressBookCheckVersion.plist" params:nil success:^(id json) {
               NSDictionary *versionPlist = [CYTool plistData:json];
               if (versionPlist && versionPlist[@"appVersion"] != nil) {
                    NSString *version = versionPlist[@"appVersion"];
                    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
                    if (![version isEqualToString:appVersion]) {
                         [UMCheckUpdate checkUpdateWithAppkey:UMAppkey channel:nil];
                    }
               }
          } failure:^(NSError *error) {
               CYLog(@"检查version更新错误: %@", error);
          }];
          
          //云同x步
          [CYMeTool backgroundCloudSyn];
          //初始化数据库
          [[CYDatabase sharedDatabase] prepareDatabase];
          //初始化通话中心
          [CYCallCenter sharedCallCenter];
          //每日启动
          [CYABTool jfshopWithType:@"0" success:nil failure:^(NSError *error) {
               CYLog(@"每日启动积分添加错误: %@", error);
          }];
          //集成bugly
          [[CrashReporter sharedInstance] enableLog:YES];
          //store版900017864  企业级:900014614
          [[CrashReporter sharedInstance] installWithAppId:@"900017864"];
     }
     @catch (NSException *exception) {
          [self reportException:exception];
          //        [[CrashReporter sharedInstance] reportException:exception reason:@"AppDelegate初始化错误" extraInfo:nil];
          CYLog(@"初始化错误: %@", exception);
          NSParameterAssert(nil);
     }
     return YES;
}

-(void)tagsAliasCallback:(NSString *)alias{
     
     CYLog(@"alias = %@",alias);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
     /// Required - 注册 DeviceToken
     [JPUSHService registerDeviceToken:deviceToken];
     
     //别名
//     CYUser *user = [CYLoginHttpTool userData].user;
//     if (user&&user.userId) {
//          [JPUSHService setAlias:user.userId callbackSelector:@selector(tagsAliasCallback:) object:nil];
//
//     }
     
     CYUser *user = [CYLoginHttpTool  userData].user;
     NSString *userId = user.userId;
     userId = [userId replaceAll:@"-" with:@""];
     CYLog(@"userid = %@",userId);
     if (![user.userId isEqualToString:@""]) {
          //别名
//          [JPUSHService setTags:nil alias:userId fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//               NSString *alias = iAlias;
//               CYLog(@"alias = %@",alias);
//          }];
          [JPUSHService setTags:nil aliasInbackground:userId];

     }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
     
     CYLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
     
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
     
     // 取得 APNs 标准信息内容
     NSDictionary *aps = [userInfo valueForKey:@"aps"];
     NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
     // Required
     CYUser *user = [CYLoginHttpTool userData].user;
     if (content) {
          user.newstype = @"1";
     }else if(!content){
          user.newstype = @"2";
     }
     //     [UMessage didReceiveRemoteNotification:userInfo];
}

//后台模式 真后台
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
     
     //收到消息时
     self.isHaveJPNews = YES;
     //创建通知对象
     NSNotification *notification = [NSNotification notificationWithName:@"item" object:self];
     //发送通知
     NSNotificationCenter  * notificationCenter = [ NSNotificationCenter  defaultCenter];
     [notificationCenter postNotification:notification];
     
     CYUser *user = [CYLoginHttpTool  userData].user;
     completionHandler(UIBackgroundFetchResultNoData);
     NSString *userId = user.userId;
     userId = [userId replaceAll:@"-" with:@""];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"CYPushNotification" object:self
                                                       userInfo:nil];
     CYLog(@"userid = %@",userId);
     if (![user.userId isEqualToString:@""]) {
          
          [JPUSHService setTags:nil aliasInbackground:userId];
          
     }
     
}

- (void)applicationWillResignActive:(UIApplication *)application {
     
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
     
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
     
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
     
     //后台-前台is here!!!
     NSString * string = [NSString stringWithFormat:@"%ld",(long)[UIApplication sharedApplication].applicationIconBadgeNumber];
     
     if (string.intValue==1) {
          
          //do something
          self.isHaveJPNews = YES;
          //创建通知对象
          NSNotification *notification = [NSNotification notificationWithName:@"item" object:self];
          
          //发送通知
          NSNotificationCenter  * notificationCenter = [ NSNotificationCenter  defaultCenter];
          [notificationCenter postNotification:notification];
          
     }
     
}

- (void)applicationWillTerminate:(UIApplication *)application {
     
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
     return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
     return  [UMSocialSnsService handleOpenURL:url];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
     //停止下载所有图片
     [[SDWebImageManager sharedManager] cancelAll];
     //清除内存中的图片
     [[SDWebImageManager sharedManager].imageCache clearMemory];
}
- (void)dealloc {
     [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];
}



@end
